package cn.gz.template;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

/**
 * 项目名称：idea-plugin-demo
 * <br>类描述：
 * <br>创建人：htliu
 * <br>创建时间：2018/9/8 19:58
 * <br>修改人:
 * <br>修改时间：2018/9/8 19:58
 * <br>修改备注：
 *
 * @author htliu
 * @date 2018/9/8 19:58
 */
public class GenerateIf extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent event) {
        // TODO: insert action logic here
        PsiFile file = event.getData(PlatformDataKeys.PSI_FILE);
        PsiClass clazz = (PsiClass) Arrays.stream(file.getChildren()).filter(v -> v instanceof PsiClass).collect(Collectors.toList()).get(0);
        StringBuilder builder = new StringBuilder();
        String result = Arrays.stream(clazz.getFields())
                .map(m -> {
                    String name = m.getName();
                    return MessageFormat.format("    <if test=\"{0} != null\">{1}=#{2},</if>", name, Util.camelToUnderline(name), "{" + name + "}");
                }).reduce(new BinaryOperator<String>() {
                    @Override
                    public String apply(String s, String s2) {
                        return s + "\n" + s2;
                    }
                }).orElse("");
        builder.append(result);
        String message = builder.toString();
        Messages.showMessageDialog(event.getProject(), message, "update", Messages.getInformationIcon());
    }
}
